package com.ruoyi.an.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.ruoyi.an.domain.AnWechatUser;
import com.ruoyi.an.domain.AnWechatUserMechanism;
import com.ruoyi.common.utils.CertificateNoUtil;

import java.util.HashMap;
import java.util.Map;

public class AnPlatformUtil {

    //    public static String evaluationHost = "http://39.105.54.160:5102";
    public static String evaluationHost = "https://sgapi.brainsources.com";
    public static String evaluationWebHost = "https://outscale.brainsources.cn";

    /**
     * 开始测评
     *
     * @param outTradeNo
     * @param timestamp
     * @return
     */
    public static String requestPlatformQuestion(String evaluationHost, String outTradeNo, AnWechatUser anWechatUser, String timestamp) {
        String body = null;
        try {
            Map<String, String> params = new HashMap<>();
            params.put("merchantNo", "M10000002");
            params.put("productNo", "P1000001");
            params.put("outTradeNo", outTradeNo);
            params.put("merchantUserId", anWechatUser.getWechatUserId() + "");
            params.put("headImgUrl", anWechatUser.getUserIcon());
            params.put("nickName", anWechatUser.getUserName());
            params.put("age", anWechatUser.getAge() + "");
            params.put("phone", anWechatUser.getPhone());
            params.put("sex", anWechatUser.getSex() == 0 ? "MAN" : "WOMAN");
            params.put("timestamp", timestamp);
            String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMwfkF89ZXSf2FM6LE2pKImCn7bcNCsSA871wujWopC1B6rPF4vJdiyXzDHby0ipwf/MFqffpctx5+7+buNc/EuKVRysVvEfAQL1AGUGmNijNJPG4Xyf+uaR3bFnpwsTSxldkzzH9q5X8vPzAS5yUjisJOdWEfYPmPH9O7xqlCaXAgMBAAECgYEAgc+48riK4uYcnqEqN6FSJFEr3RChJJrqTR3B/G0zKS/XVmspID7YpndK5pJO70D2HQTfi5cRSxZ/V1/7iSBDWWwSXxYOSxqcj3Xti3niL/+WBSa7Lxzrunkjwv6dk9kbAakBMDAFd2F6T14/QRUOfUlRFPOHoxtLruzZh3JdcQECQQDsGCWdNvAtKh8dpr0w+lqfo+qg7rITPDavKIWU3H7jRaKG03GWlZURE4vxSiFCPNhoyeXzl4LI3oxN7a2ml91BAkEA3VVa9I6est7NBo3R5o/M7pUwcmTOW32R3ms9xNtcygdjYUDl7d1sU98q7IhQAI6JmigYnHh383U1akMozCMV1wJBANI1AbCDzL55xXCSF9r23R9MQ8h8HkMwFoRH8P/Efpl+U6H1uynXDv1ASRZR6WDfadOLB9ml6cVNGOD9oOI2TsECQDQiX9tNIMqHOon5q+CALMhh8dhwMD9Ss6JNZm5RMWkRFnKZA8/koRicb5LphNasvHLIUQvCQJbjG+Lc0OZMuV8CQAJE7amTeT1FOD1HtuYTUYWUBzs/psnSxMXFqvwox1HBiK5wtBsMXT71OfeZxX+njR2ahqc2XzZ60hF6Kbi4xBk=";
            String charset = "UTF-8";
            String sign = AlipaySignature.rsaSign(params, privateKey, charset);
            JSONObject object = JSONObject.parseObject(JSON.toJSONString(params));
            object.put("signature", sign);
            HttpRequest post = HttpUtil.createPost(evaluationHost + "/platform/transactions");
            post.contentType("application/json");
            post.body(object.toJSONString());
            HttpResponse execute = post.execute();
            body = execute.body();
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        return body;
    }

    public static JSONObject requestNewPlatformQuestion(AnWechatUser anWechatUser) {
        JSONObject result = new JSONObject();
        Map<String, String> params = new HashMap<>();
        params.put("idCard", anWechatUser.getUserCardId());
        params.put("patientName", anWechatUser.getUserName());
        params.put("merchantUserId", anWechatUser.getWechatUserId() + "");
        params.put("headImgUrl", anWechatUser.getUserIcon());
        Map<String, String> birAgeSex = CertificateNoUtil.getBirAgeSex(anWechatUser.getUserCardId());
        params.put("birthDay", birAgeSex.get("birthday"));
        params.put("mobileNo", anWechatUser.getPhone());
        String education = convertEducation(anWechatUser.getEducation());
        params.put("educationId", education);
        params.put("marryId", anWechatUser.getMarriage() + "");
        params.put("jobId", anWechatUser.getOccupation());
        params.put("sex", anWechatUser.getSex() == 1 ? "1" : "2");
        JSONObject object = JSONObject.parseObject(JSON.toJSONString(params));
        HttpRequest post = HttpUtil.createPost(evaluationHost + "/system/api/patient/savePatient");
        post.contentType("application/json");
        post.body(object.toJSONString());
        HttpResponse execute = post.execute();
        String body = execute.body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        try {
            JSONObject data = jsonObject.getJSONObject("data");
            String patientId = data.getString("patientId");
            String doctorId = data.getString("doctorId");
            String token = data.getString("token");
            String url = evaluationWebHost + "?token=" + token + "&patientId=" + patientId + "&doctorId=" + doctorId + "";
            result.put("url", url);
            result.put("patientId", patientId);
            result.put("doctorId", doctorId);
            result.put("token", token);
            return result;
        } catch (Exception e) {
            return jsonObject;
        }
    }

    private static String convertEducation(String education) {
        String resultEducation = "";
        switch (education) {
            case "0":
            case "1":
                resultEducation = "98";
                break;
            case "2":
                resultEducation = "2";
                break;
            case "3":
                resultEducation = "4";
                break;
            case "4":
                resultEducation = "113";
                break;
            case "5":
                resultEducation = "115";
                break;
            case "6":
                resultEducation = "118";
                break;
            case "7":
                resultEducation = "121";
                break;
        }
        return resultEducation;
    }

    public static JSONObject requestNewPlatformQuestionReport(AnWechatUserMechanism anWechatUserMechanism) {
        HttpRequest get = HttpUtil.createGet(evaluationHost + "/system/api/patient/getReport?patientId=" + anWechatUserMechanism.getOutTradeNo());
        get.header("Authorization", "Bearer " + anWechatUserMechanism.getTradeNo());
        HttpResponse execute = get.execute();
        String body = execute.body();
        return JSONObject.parseObject(body);
    }

    /**
     * 查询测评结果
     *
     * @param outTradeNo
     * @param timestamp
     * @return
     */
    public static String requestPlatformQuestionReport(String evaluationHost, String outTradeNo, String timestamp) {
        String body = null;
        try {
            Map<String, String> params = new HashMap<>();
            params.put("merchantNo", "M10000002");
            params.put("outTradeNo", outTradeNo);
            params.put("timestamp", timestamp);
            String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMwfkF89ZXSf2FM6LE2pKImCn7bcNCsSA871wujWopC1B6rPF4vJdiyXzDHby0ipwf/MFqffpctx5+7+buNc/EuKVRysVvEfAQL1AGUGmNijNJPG4Xyf+uaR3bFnpwsTSxldkzzH9q5X8vPzAS5yUjisJOdWEfYPmPH9O7xqlCaXAgMBAAECgYEAgc+48riK4uYcnqEqN6FSJFEr3RChJJrqTR3B/G0zKS/XVmspID7YpndK5pJO70D2HQTfi5cRSxZ/V1/7iSBDWWwSXxYOSxqcj3Xti3niL/+WBSa7Lxzrunkjwv6dk9kbAakBMDAFd2F6T14/QRUOfUlRFPOHoxtLruzZh3JdcQECQQDsGCWdNvAtKh8dpr0w+lqfo+qg7rITPDavKIWU3H7jRaKG03GWlZURE4vxSiFCPNhoyeXzl4LI3oxN7a2ml91BAkEA3VVa9I6est7NBo3R5o/M7pUwcmTOW32R3ms9xNtcygdjYUDl7d1sU98q7IhQAI6JmigYnHh383U1akMozCMV1wJBANI1AbCDzL55xXCSF9r23R9MQ8h8HkMwFoRH8P/Efpl+U6H1uynXDv1ASRZR6WDfadOLB9ml6cVNGOD9oOI2TsECQDQiX9tNIMqHOon5q+CALMhh8dhwMD9Ss6JNZm5RMWkRFnKZA8/koRicb5LphNasvHLIUQvCQJbjG+Lc0OZMuV8CQAJE7amTeT1FOD1HtuYTUYWUBzs/psnSxMXFqvwox1HBiK5wtBsMXT71OfeZxX+njR2ahqc2XzZ60hF6Kbi4xBk=";
            String charset = "UTF-8";
            String sign = AlipaySignature.rsaSign(params, privateKey, charset);
            JSONObject object = JSONObject.parseObject(JSON.toJSONString(params));
            object.put("signature", sign);
            HttpRequest post = HttpUtil.createPost(evaluationHost + "/platform/queryreport");
            post.contentType("application/json");
            post.body(object.toJSONString());
            HttpResponse execute = post.execute();
            body = execute.body();
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        return body;
    }

    public static String requestPlatformQuestionEvaluationStage(String evaluationHost, String outTradeNo) {
        String body = null;
        try {
            Map<String, String> params = new HashMap<>();
            params.put("merchantNo", "M10000002");
            params.put("outTradeNo", outTradeNo);
            String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMwfkF89ZXSf2FM6LE2pKImCn7bcNCsSA871wujWopC1B6rPF4vJdiyXzDHby0ipwf/MFqffpctx5+7+buNc/EuKVRysVvEfAQL1AGUGmNijNJPG4Xyf+uaR3bFnpwsTSxldkzzH9q5X8vPzAS5yUjisJOdWEfYPmPH9O7xqlCaXAgMBAAECgYEAgc+48riK4uYcnqEqN6FSJFEr3RChJJrqTR3B/G0zKS/XVmspID7YpndK5pJO70D2HQTfi5cRSxZ/V1/7iSBDWWwSXxYOSxqcj3Xti3niL/+WBSa7Lxzrunkjwv6dk9kbAakBMDAFd2F6T14/QRUOfUlRFPOHoxtLruzZh3JdcQECQQDsGCWdNvAtKh8dpr0w+lqfo+qg7rITPDavKIWU3H7jRaKG03GWlZURE4vxSiFCPNhoyeXzl4LI3oxN7a2ml91BAkEA3VVa9I6est7NBo3R5o/M7pUwcmTOW32R3ms9xNtcygdjYUDl7d1sU98q7IhQAI6JmigYnHh383U1akMozCMV1wJBANI1AbCDzL55xXCSF9r23R9MQ8h8HkMwFoRH8P/Efpl+U6H1uynXDv1ASRZR6WDfadOLB9ml6cVNGOD9oOI2TsECQDQiX9tNIMqHOon5q+CALMhh8dhwMD9Ss6JNZm5RMWkRFnKZA8/koRicb5LphNasvHLIUQvCQJbjG+Lc0OZMuV8CQAJE7amTeT1FOD1HtuYTUYWUBzs/psnSxMXFqvwox1HBiK5wtBsMXT71OfeZxX+njR2ahqc2XzZ60hF6Kbi4xBk=";
            String charset = "UTF-8";
            String sign = AlipaySignature.rsaSign(params, privateKey, charset);
            JSONObject object = JSONObject.parseObject(JSON.toJSONString(params));
            object.put("signature", sign);
            HttpRequest post = HttpUtil.createPost(evaluationHost + "/platform/queryevaluationstage");
            post.contentType("application/json");
            post.body(object.toJSONString());
            HttpResponse execute = post.execute();
            body = execute.body();
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        return body;
    }

    public static String requestPlatformQuestionReportInfo(String evaluationWebViewHost, String secret) {
        String url = evaluationWebViewHost + "/brain/wx/getcognitivereportpdf";
        HttpRequest get = HttpUtil.createGet(url);
        get.header("Secret", secret);
        HttpResponse execute = get.execute();
        String body = execute.body();
        return body;
    }


    public static void main(String[] args) {
//        String json = "{ \"searchValue\": null, \"createBy\": \"\", \"createTime\": \"2022-11-07 19:45:53\", \"updateBy\": \"admin\", \"updateTime\": \"2022-11-18 20:37:06\", \"remark\": null, \"params\": {}, \"wechatUserId\": 1003, \"nickName\": \"文刂 走召 杰\uD83D\uDC2F\", \"userName\": \"asdf\", \"userIcon\": \"https://www.ainaoxingdong.com/api/an-media/images/3337550046806.jpeg\", \"sex\": 0, \"userCardId\": \"410183199812025204\", \"age\": 24, \"education\": \"0\", \"phone\": \"15555555555\", \"isDone\": null, \"screeningScore\": null, \"screeningSource\": \"晓明22有限责任公司-afdasf\", \"isMechanism\": 0, \"marriage\": 0, \"occupation\": \"0\", \"authTime\": null, \"address\": \"北京市市辖区东城区\", \"openId\": \"oEuYG48TyxoTluI3CSI3No3C76VI\", \"promotionCode\": null }";
//        AnWechatUser anWechatUser = JSONObject.parseObject(json).toJavaObject(AnWechatUser.class);
//        JSONObject result = requestNewPlatformQuestion(anWechatUser);
//        System.out.println(result.toJSONString());
        AnWechatUserMechanism anWechatUserMechanism = new AnWechatUserMechanism();
        anWechatUserMechanism.setTradeNo("9335c976-c2df-407b-aaf5-aa84b72bc387");
        anWechatUserMechanism.setOutTradeNo("ed661f49280b49df9332eb0b353e3b7f");
        JSONObject object = requestNewPlatformQuestionReport(anWechatUserMechanism);
        System.out.println(object.toJSONString());
    }
}
